package cn.bopomo.dealer.base.action.ajax;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.bopomo.dealer.base.action.BaseAction;
import cn.bopomo.dealer.base.common.ServiceConfig;
import cn.bopomo.dealer.base.service.IOperatorService;
import cn.bopomo.dealer.base.vo.AuGroup;
import cn.bopomo.dealer.base.vo.AuthorizeList;
import cn.bopomo.dealer.base.vo.ModuleList;

public class LoadGroupByGidAjax extends BaseAction {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control","no-cache");
		
		IOperatorService os = (IOperatorService)this.findService(ServiceConfig.OPERATOR_SERVICE);
		String moduleId = request.getParameter("gid");
		
		
		AuGroup group = os.getGroup(new Integer(moduleId));
		if (group == null)
			return null;
		
		ModuleList module = group.getModuleList();
		if (module == null)
			module = os.getModule(group.getModuleList().getMid());
		List authorizeList = os.getAuthorizesByModule(module.getMid());
		JSONObject json = new JSONObject();
		json.put("groupAuthorize",group.getGroupAuthorize());
		json.put("groupName",group.getGroupName());
		json.put("id",group.getId().toString());
		json.put("mid",group.getModuleList().getMid().toString());
		this.authorizeFilter(authorizeList,json,group.getGroupAuthorize());
		
		response.getWriter().write(json.toString());
		return null;
		
		
		
	}

	private void authorizeFilter(List authorizeList, JSONObject json, String groupAuthorize){
		JSONArray fromArray = new JSONArray();
		JSONArray toArray = new JSONArray();
		for (Iterator it = authorizeList.iterator();it.hasNext();){
			AuthorizeList tmp = (AuthorizeList)it.next();
			JSONObject authorizeJson = new JSONObject();
			authorizeJson.put("tag",tmp.getAuthorizeTag());
			authorizeJson.put("authorizeName",tmp.getAuthorizeName());
			if (groupAuthorize.indexOf(tmp.getAuthorizeTag()) == -1)
				fromArray.put(authorizeJson);
			else
				toArray.put(authorizeJson);
		}
		json.put("fromArray",fromArray);
		json.put("toArray",toArray);
	}
	
}
